package com.icongyou.enterprise.talent_analysis.scheduler;

import com.icongyou.enterprise.talent_analysis.entity.WordCloudUpdateQueue;
import com.icongyou.enterprise.talent_analysis.mapper.WordCloudUpdateQueueMapper;
import com.icongyou.enterprise.talent_analysis.service.WordCloudService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 词云图异步生成调度器（独立于画像生成调度器）
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WordCloudGenerationScheduler {
    
    private final WordCloudUpdateQueueMapper queueMapper;
    private final WordCloudService wordCloudService;
    
    /**
     * 每10秒检查一次待处理的词云图生成任务
     */
    @Scheduled(fixedDelay = 10000)
    public void processWordCloudQueue() {
        try {
            List<WordCloudUpdateQueue> tasks = queueMapper.selectPendingTasks(10);
            
            if (tasks.isEmpty()) {
                return;
            }
            
            
            for (WordCloudUpdateQueue task : tasks) {
                processTask(task);
            }
            
        } catch (Exception e) {
        }
    }
    
    /**
     * 处理单个任务
     */
    private void processTask(WordCloudUpdateQueue task) {
        try {
            
            // 更新状态为处理中
            queueMapper.updateToProcessing(task.getId());
            
            // 同步生成词云图
            wordCloudService.generateWordCloudSync(task.getStudentId());
            
            // 更新状态为完成
            queueMapper.updateToCompleted(task.getId());
            
            
        } catch (Exception e) {
            
            // 增加重试次数
            queueMapper.incrementRetryCount(task.getId());
            
            // 如果重试次数超过3次，标记为失败
            if (task.getRetryCount() >= 2) {
                queueMapper.updateToFailed(task.getId(), e.getMessage());
            }
        }
    }
}
